package com.xxx.common.sentinel.configure;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
        // 根据规则类型返回不同消息
        String msg = "请求被拒绝";
        int status = 429; // HTTP 429 Too Many Requests

        if (ex instanceof FlowException) {
            msg = "接口限流了，请稍后重试";
        } else if (ex instanceof DegradeException) {
            msg = "服务熔断了，请稍后重试";
        } else if (ex instanceof ParamFlowException) {
            msg = "热点参数限流";
        } else if (ex instanceof SystemBlockException) {
            msg = "系统规则（如CPU负载）触发限流";
        }

        // 返回JSON格式的响应
        response.setStatus(status);
        response.setContentType("application/json;charset=utf-8");

        Map<String, Object> result = new HashMap<>();
        result.put("code", status);
        result.put("message", msg);
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}